<template>
  <div class="wrap">
    <el-card class="header-card">
      <div class="item">
        <p>{{ $t('table.store') }}：{{data.accountName}}</p>
        <p >{{ $t('table.送仓单号') }}：{{ data.workNo }}</p>
        <p v-if="data.labelOrder">{{ $t('table.贴标单号') }}：{{data.labelOrder.labelNo}}</p>
        <p>{{$t('table.warehouse')}}：{{data.warehouseName}}</p>
        <p>{{$t('middle.送仓方式')}}：{{getMiddleSendTypeStr(data.sendType)}}</p>
        <p class="">{{ $t('table.工单状态') }}：{{ getMiddleStatus(data.status, data.cancel) }}</p>
        <p class="" v-if="data.labelOrder">{{ $t('table.贴标状态') }}：{{ data.labelStatus === 0 ? $t('shipment.无需贴标') : getLabelStatusStr(data.labelOrder.status)}}</p>
        <p>
          <span>{{ $t('table.createTime2') }}：{{ data.createTime }}</span>
          <span class="mgl20" v-if="data.pickedTime">{{ $t('table.拣货时间') }}：{{ data.pickedTime }}</span>
          <span class="mgl20" v-if="data.sendTime">{{ $t('table.送仓时间') }}：{{ data.sendTime }}</span>
          <span class="mgl20" v-if="data.cancelTime">{{ $t('table.重新入库时间') }}：{{ data.cancelTime }}</span>
        </p>
        <p>
          <span>{{$t('table.箱子数量')}}：{{data.boxNum}}</span>
          <span class="mgl20">
            {{$t('table.SKU种数')}}：
            <template v-if="data.status > 2">
              {{ data.rlSkuNum }}
            </template>
            <template v-else>
               {{ data.exSkuNum }}
            </template>
          </span>
          <span class="mgl20">
            {{$t('table.商品总数量')}}:
            <template v-if="data.status > 2">
              {{ data.rlGoodsNum }}
            </template>
            <template v-else>
              {{ data.exGoodsNum }}
            </template>
          </span>
        </p>
        <p v-if="data.labelOrder">

        </p>
       <!-- <p>
          <span>
            {{$t('table.送仓费用（元）')}}:
            <span class="font-green" v-if="data.returnFee === 1">
              {{ data.transfer2warehouse }}（{{$t('order.Returned')}}）
            </span>
            <span v-else>
            {{ data.transfer2warehouse }}
            </span>
          </span> -->
         <!-- <template v-if="data.sendType === 2">
            <span class="mgl20">
              {{$t('table.包车费用（元）')}}：
            </span>
            <template v-if="data.returnCarFee === 1">
              <span class="font-green">{{data.charteredCarFee}} （{{$t('order.Returned')}}）</span>
            </template>
            <template v-else>
              <span>{{data.charteredCarFee}}</span>
            </template>
          </template>
          <template v-if="data.labelOrder">
            <span class="mgl20">{{ $t('table.贴SKU标费用（元）') }}：
              <template v-if="data.labelOrder.status === 2">
                <template v-if="data.labelOrder.returnFee === 1">
                  <span class="font-red">{{ data.labelOrder.rlTotalLabelFee }} （{{$t('order.Returned')}}）</span>
                </template>
                <template v-else>
                  {{ data.labelOrder.rlTotalLabelFee }}
                </template>
              </template>
              <template v-else>
                {{ data.labelOrder.exTotalLabelFee }}
              </template>

            </span>
          </template>
          <span class="mgl20">
            {{$t('table.贴外箱标费用（元）')}}:
            <span class="font-green" v-if="data.returnBoxFee === 1">
                {{ data.boxLabelFee }}（{{$t('order.Returned')}}）
            </span>
            <span v-else>
              {{ data.boxLabelFee }}
            </span>
          </span>

        </p>
        <p v-if="data.status < 2">
          {{$t('table.预计总费用（元）')}}：{{data.exTotalFee}}
        </p>
        <p v-else>
          {{$t('table.总费用（元）')}}：{{data.rlTotalFee}}
        </p> -->
        <p v-if="data.child_id!=''&&data.child_id!=0&&data.child_id!=null">
          <span >操作员：{{ data.child_name }}</span>
        </p>
        <p v-else>
          <span >操作员：{{ data.userAccount }}</span>
        </p>
      </div>
      <div class="button">
        <div v-if="data.labelOrder">
          <el-button type="primary" @click="jumpLabelOrderInfo(data.labelOrder.id, true)">{{ $t('labelOrder.贴标工单') }}</el-button>
        </div>
      </div>
    </el-card>

    <div class="mgt20">
       <h4>{{ $t('middle.费用信息') }}</h4>
        <el-table
             :data="exFee"
             border
             style="width: 100%">
             <el-table-column
               prop="exTransferFee"
               :label="$t('table.送仓费用（元）')"
               min-width="180"
               align="center">
               <template >
                 <span class="font-green" v-if="data.returnFee === 1">
                   {{ data.transfer2warehouse }}（{{$t('order.Returned')}}）
                 </span>
                 <span v-else>
                 {{ data.transfer2warehouse }}
                 </span>
               </template>
             </el-table-column>
             <el-table-column
               prop="exTotalLabelFee"
                :label="$t('table.包车费用（元）')"
               min-width="180"
               align="center">

                <template v-if="data.returnCarFee === 1">
                  <span class="font-green">{{data.charteredCarFee}} （{{$t('order.Returned')}}）</span>
                </template>
                <template v-else>
                  <span>{{data.charteredCarFee}}</span>
                </template>

             </el-table-column>
             <el-table-column
               prop="exTotalFee"
              :label="$t('table.贴SKU标费用（元）')"
              min-width="180"
              align="center"
              v-if="data.labelOrder">
            <template v-if="data.labelOrder.status === 2">
              <template v-if="data.labelOrder.returnFee === 1">
                <span class="font-red">{{ data.labelOrder.rlTotalLabelFee }} （{{$t('order.Returned')}}）</span>
              </template>
              <template v-else>
                {{ data.labelOrder.rlTotalLabelFee }}
              </template>
            </template>
            <template v-else>
              {{ data.labelOrder.exTotalLabelFee }}
            </template>
             </el-table-column>
             <el-table-column
               prop="exTotalFee"
              :label="$t('table.贴外箱标费用（元）')"
              min-width="180"
              align="center">
             <template >
              <span class="font-green" v-if="data.returnBoxFee === 1">
                  {{ data.boxLabelFee }}（{{$t('order.Returned')}}）
              </span>
              <span v-else>
                {{ data.boxLabelFee }}
              </span>
             </template>
             </el-table-column>

             <el-table-column
               prop="exTotalFee"
              :label="$t('table.总费用（元）')"
              min-width="180"
              align="center">
             <template >
              <p v-if="data.status < 2">
               {{data.exTotalFee}}
              </p>
              <p v-else>
               {{data.rlTotalFee}}
              </p>
             </template>
             </el-table-column>
           </el-table>
    </div>

    <div>
<!--     <div v-if="straightGoods.length > 0">
        <h4>{{ $t('middle.无需调货贴标商品详细情况') }}：</h4>
        <el-table
          :data="straightGoods"
          row-key="id"
          border
          style="width: 1400px"
        >
          <el-table-column
            :label="$t('table.productCover')"
            align="center"
            width="120"
            fixed="left"
          >
            <template slot-scope="{row}">
              <div class="img-box img-one">
                <img :src="row.image" alt="">
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('table.title')"
            align="left"
            min-width="300"
          >
            <template slot-scope="{row}">
              {{row.title}}
              <div class="goods-SKU-info">
                <span
                  v-for="attr in row.attributes"
                  :key="attr.name"
                  class="attr"
                >
                  {{attr.name}} : {{attr.value}}
                  <span class="attr-link"> | </span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('table.ListingIDAndSKU')"
            align="left"
            min-width="300"
          >
            <template slot-scope="{row}">
              {{row.goodsId}}{{row.sku ? `(${row.sku})` : ''}}
            </template>
          </el-table-column>
          <m-l-code-column></m-l-code-column>
          <el-table-column
            :label="$t('table.预计从中转送仓调出')"
            align="center"
            width="200"
            prop="boxInfo"
          >
            <template v-slot="{row}">
              <div
                v-for="(item,index) in row.boxInfo"
                :key="index"
              >
                {{$t('table.num/箱',{num: item.goodsNumInBox})}} × {{item.editNum}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('table.预计中转送仓数量')"
            align="center"
            width="200"
            prop="exGoodsNum"
          >
          </el-table-column>
          <el-table-column
            v-if="data.status > 1"
            :label="$t('table.实际中转送仓数量')"
            align="center"
            width="200"
            prop="rlGoodsNum"
          >
            <template v-slot="{row}">
              <span :class="[row.rlGoodsNum !== row.exGoodsNum ? 'font-red' : '']">{{row.rlGoodsNum}}</span>
            </template>
          </el-table-column>

        </el-table>
      </div> -->


      <div v-if="GoodsList.length > 0">
        <!-- <h4>{{ $t('middle.需调货贴标商品详细情况') }}：</h4> -->
        <h4>送仓商品详情：</h4>
        <el-table
          :data="GoodsList"
          row-key="id"
          border
          :span-method="objectSpanMethod1"
        >
          <el-table-column
            :label="$t('table.productCover')"
            align="center"
            width="120"
            fixed="left"
            prop="image"
          >
            <template slot-scope="{row}">
              <div class="img-box img-one">
                <img :src="row.image" alt="">
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('table.title')"
            align="left"
            min-width="300"
            prop="title"
          >
            <template slot-scope="{row}">
              {{row.title}}
              <div class="goods-SKU-info">
                <span
                  v-for="attr in row.attributes"
                  :key="attr.name"
                  class="attr"
                >
                  {{attr.name}} : {{attr.value}}
                  <span class="attr-link"> | </span>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('table.ListingIDAndSKU')"
            align="left"
            min-width="300"
            prop="toGoodsId"
          >
            <template slot-scope="{row}">
              {{row.goodsId}}{{row.sku ? `(${row.sku})` : ''}}
            </template>
          </el-table-column>
          <!-- <m-l-code-column></m-l-code-column> -->
          <el-table-column
            label="产品标"
            align="left"
            width="200"
            prop="fromGoodsId"
          >
            <template v-slot="{row}">
              <template v-if="row.fromGoodsIsTB">
                {{$t('shipment.Not labeled')}}
              </template>
              <template v-else>
               {{row.fromInventoryId ? `${row.fromInventoryId}` : ''}}
              </template>
            </template>
          </el-table-column>
          <!-- <m-l-code-column prop="fromInventoryId" :label="$t('table.调货MLCode')"></m-l-code-column> -->
          <el-table-column
            :label="$t('table.预计从中转送仓调出')"
            align="center"
            width="200"
            prop="boxInfo"
          >
            <template v-slot="{row}">
              <div
                v-for="(item,index) in row.boxInfo"
                :key="index"
              >
                {{$t('table.num/箱',{num: item.goodsNumInBox})}} × {{item.editNum}}
              </div>
            </template>
          </el-table-column>
       <!--   <template v-if="data.status > 1">
            <el-table-column
              :label="$t('table.实际调出数量')"
              align="center"
              width="200"
              prop="rlGoodsNum"
            >
              <template v-slot="{row}">
                <span :class="row.rlGoodsNum === row.exGoodsNum ? '' : 'font-red'">{{row.rlGoodsNum}}</span>
              </template>
            </el-table-column>
          </template> -->
          <el-table-column
            :label="$t('table.预计送仓商品总数量')"
            align="center"
            width="200"
            prop="exGoodsNum"
          >

          </el-table-column>
          <template v-if="data.status > 1">
            <el-table-column
              :label="$t('table.实际送仓商品总数量')"
              align="center"
              width="200"
              prop="totalRlGoodsNum"
            >
              <template v-slot="{row}">
                <span :class="row.rlGoodsNum === row.needDistributionNum ? '' : 'font-red'">{{row.rlGoodsNum}}</span>
                  <!-- {{getRlTotalGoodsNum(row)}} -->
              </template>
            </el-table-column>
          </template>


        </el-table>
      </div>



    </div>

    <div class="mgt20">
      <div class="font-bold f14">{{ $t('middle.箱标') }}</div>
      <div class="box-content f14 font-grey">
        <div style="margin-top:5px">
          {{ $t('middle.请根据本次送仓箱子数量到美客多后台添加送仓货件获取箱标并在此处上传，以供仓库人员打印粘贴送仓') }}
        </div>
      </div>
      <upload-middle-file
        class="mgt10"
        :file="data.boxPDF"
        :upload-file-text="$t('common.上传文件')"
        :edit-file-text="$t('common.修改文件')"
        @uploadFileSuccess="uploadBoxPDFSuccess"
        :can-upload="data.status <= 1"
      ></upload-middle-file>
    </div>

    <div class="mgt20" v-if="data.status <= 1 || data.middlePDF">
      <div class="font-bold f14">{{ $t('middle.送仓单') }}</div>
      <div class="box-content f14 font-grey">
        <div style="margin-top:5px">
          {{ $t('middle.本土店铺如由卖家预约送仓，请上传送仓单。跨境店铺请忽略') }}
        </div>
      </div>
      <upload-middle-file
        class="mgt10"
        :file="data.middlePDF"
        :upload-file-text="$t('common.上传文件')"
        :edit-file-text="$t('common.修改文件')"
        @uploadFileSuccess="uploadMiddlePdfSuccess"
        :can-upload="data.status <= 1"
      ></upload-middle-file>
    </div>

    <div class="remark">
      <h4>{{$t('shipment.step4Text10')}}：</h4>
      <el-input type="textarea" style="width: 1500px" :placeholder="$t('shipment.step4Text11')" v-model="data.remark"></el-input>
    </div>

    <el-dialog
      :title="$t('middle.选择调货库存')"
      :visible.sync="distributionDialog"
      width="1000px"
    >
      <div>
        <div>{{ $t('middle.请选择填写从那个库存调出到本次中转') }}</div>
        <div>{{ $t('table.需要调货数量') }}: {{distributionGoods.needDistributionNum}}</div>
        <el-table
          :data="distributionGoods.otherGoodsList ? distributionGoods.otherGoodsList : []"
          row-key="id"
          border
        >
          <el-table-column
            :label="$t('table.ListingIDAndSKU')"
            align="left"
            min-width="300"
            show-overflow-tooltip
          >
            <template slot-scope="{row}">
              <template v-if="row.isGoods">
                {{row.goodsId}}{{row.sku ? `(${row.sku})` : ''}}
              </template>
              <template v-else>
                {{ $t('shipment.Not labeled') }}
              </template>
            </template>
          </el-table-column>
          <m-l-code-column></m-l-code-column>
          <el-table-column
            :label="$t('table.当前店铺中转送仓库存')"
            align="center"
            width="200"
            prop="middleStockNum"
          >
          </el-table-column>
          <el-table-column
            :label="$t('table.调出库存')"
            align="center"
            width="200"
            prop="distributionNum"
          >
            <template v-slot="{row}">
              <el-input-number
                :step="1"
                :precision="0"
                :min="0"
                :max="Math.min(row.middleStockNum,distributionGoods.needDistributionNum)"
                :disabled="row.middleStockNum === 0"
                v-model="row.distributionNum"
              >
              </el-input-number>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="distributionDialog = false">{{$t('common.cancel')}}</el-button>
        <el-button type="primary" @click="addDistributionGoodsData">{{$t('common.confirm')}}</el-button>
      </div>
    </el-dialog>

    <div class="mgt20">
      <el-button @click="jumpPage('middleList')">{{ $t('common.back') }}</el-button>
      <el-button type="primary" @click="editGoodsNum" v-if="canEdit">{{ $t('common.confirmModification') }}</el-button>
      <template v-if="data.status > 1">
        <template v-if="data.cancel === 0 && data.status !== 4">
          <cancel-button :id="data.id"  @changeWorkStatus="getData"></cancel-button>
        </template>
        <template v-if="data.cancel === 1 && data.knowCancel === 0">
          <return-cancel-button :id="data.id" @changeWorkStatus="getData"></return-cancel-button>
        </template>
      </template>
    </div>
  </div>
</template>

<script>
import UploadGoodsLabel from "@/views/stock/components/UploadGoodsLabel";
import {confirmLabelOrder, editLabelOrder, getLabelOrderInfo} from "@/api/labelOrder";
import {deepCopy} from "@/utils";
import {jumpLabelOrderInfo, jumpPage, jumpShipmentInfo} from "@/utils/jumpView";
import {editMiddleWork, getMiddleInfo} from "@/api/middleWork";
import UploadBoxPDF from "@/views/middleWork/components/UploadBoxPDF.vue";
import CancelButton from "@/views/middleWork/components/CancelButton";
import ReturnCancelButton from "@/views/middleWork/components/ReturnCancelButton";
import {getLabelStatusStr} from "@/utils/labelOrder";
import {getMiddleSendTypeStr, getMiddleStatus} from "@/utils/MiddleWork";
import DivNum from "@/views/middleWork/components/DivNum.vue";
import MLCodeColumn from "@/views/stock/components/MLCodeColumn.vue";
import UploadMiddleFile from "@/views/middleWork/components/UploadMiddleFile.vue";

export default {
  name: "middleInfo",
  components: {UploadMiddleFile, MLCodeColumn, ReturnCancelButton, CancelButton, UploadBoxPDF},
  computed:{
    canEdit() {
      return this.data.status <=1 && (!this.data.labelOrder || this.data.labelOrder.status !== 2);
    }
  },
  data(){
    return {
      id: 0,
      loading: false,
      data: {},
      straightGoods: [], // 无需调货的商品
      distributionGoodsList: [], // 需要调货的商品
      distributionDialog: false,
      distributionGoods: {},
      otherGoodsList: [],
      editLoading: false,
       exFee: [{'exTotalFee':0,'exTotalLabelFee':0,'exTransferFee':0}],
      GoodsList:[],
    }
  },
  created() {
    this.id = this.$route.query.id;
    this.getData()
  },
  methods:{
    getMiddleSendTypeStr,
    getMiddleStatus,
    getLabelStatusStr,
    jumpLabelOrderInfo,jumpPage,
    getData(){
      getMiddleInfo(this.id)
        .then(res=>{
          this.data = res.data
          this.straightGoods =  res.data.straightGoods
          this.distributionGoodsList = res.data.distributionGoods
           this.GoodsList=res.data.GoodsList

        })
    },
    // 修改库存
    chooseDistribution(row){
      this.distributionDialog = true
      this.distributionGoods = deepCopy(row)
    },
    addDistributionGoodsData(){
      const needNum = this.distributionGoods.needDistributionNum
      const editNum = this.distributionGoods.otherGoodsList.reduce((prev,cur)=>{
        cur.distributionNum = cur.distributionNum ? cur.distributionNum : 0
        return prev + cur.distributionNum
      },0)
      if(needNum !== editNum){
        this.$errorMessage(`调货总数量应为${needNum}`)
        return;
      }
      let row = this.GoodsList.find(item=> item.id === this.distributionGoods.id)
      row.otherGoodsList.forEach(item=>{
        const _row = this.distributionGoods.otherGoodsList.find(_item => _item.id === item.id)
        if(_row){
          item.distributionNum = _row.distributionNum
        }
      })
      this.distributionDialog = false
    },
    objectSpanMethod1({ row, column, rowIndex, columnIndex }) {
      const mergeCell = this.mergeCell1()
      if(mergeCell[column.property]){
        if(mergeCell[column.property][rowIndex]) {
          return [mergeCell[column.property][rowIndex], 1]
        } else {
          // 如果为0则为需要合并的行
          return [0, 0];
        }
      }
    },
    mergeCell1(){
      const mergeObj = {};
      // 根据suitId合并的字段
      const mergeFieldArr = [
        'image',
        'title',
        'toGoodsId',
        'needDistributionNum',
        'operate',
        'inventoryId'
      ];

      mergeFieldArr.forEach(key=>{
        mergeObj[key] = [1];
      })

      let mergeFieldKey = 0;
      this.GoodsList.forEach((item,index)=>{
        // 第一列数据不处理
        if(index === 0){
          return;
        }
        // 根据suitId 合并
        if(item.toSuitListId && item.toSuitListId === this.GoodsList[index - 1].toSuitListId){
          mergeFieldArr.forEach(key=>{
            mergeObj[key][mergeFieldKey] += 1;
            mergeObj[key].push(0); // 添加一个0 站位
          })
        }else{
          mergeFieldKey = index; // 记录当前行
          mergeFieldArr.forEach(key=>{
            mergeObj[key].push(1); // 添加一个1
          })
        }
      })

      return mergeObj;
    },
    // 修改库存和备注
    editGoodsNum(){

      const data = {
        id: this.data.id,
        otherGoodsList: this.otherGoodsList,
        remark: this.data.remark,
        boxPDF: this.data.boxPDF,
        middlePDF: this.data.middlePDF,
      }
      // 校验数据提交是否有误
      const flag = this.otherGoodsList.every(otherGoodsItem=>{
        // 当前的总数
        const totalNum = otherGoodsItem.reduce((prev,cur)=>{
          if(!cur.distributionNum){
            cur.distributionNum = 0
          }
          return prev + cur.distributionNum
        },0)
        const currentToSuitListId = otherGoodsItem[0].toSuitListId
        let toGoodsId = ''
        let toSku = ''
        let needDistributionNum = 0
        this.distributionGoodsList.some(item=>{
          if(item.toSuitListId === currentToSuitListId){
            needDistributionNum = item.needDistributionNum
            toGoodsId = item.goodsId
            toSku = item.sku
            return true
          }
        })
        if(needDistributionNum === totalNum){
          return true
        }
        this.$errorMessage(
          this.$t('middle.调货库存不正确',{goodsStr: `${toGoodsId}(${toSku})}`})
        )
        return false
      })
      if(!flag){
        return
      }
      this.$confirm('',{
        title: this.$t('middle.确定修改当前工单？')
      })
        .then(()=>{
          this.editLoading = true
          editMiddleWork(data)
            .then(res=>{
              this.editLoading = false;
              if(res.error === 0){
                this.$successMessage(res.message)
                this.getData()
              }else{
                this.$errorMessage(res.message)
              }
            })
            .catch(()=>{
              this.editLoading = false
            })
        })
        .catch(()=>{})
    },
    // 上传箱标
    uploadBoxPDFSuccess(file){
      this.data.boxPDF = file
    },
    // 上传送仓单
    uploadMiddlePdfSuccess(file){
      this.data.middlePDF = file
    },
    // 实际调入商品总数量
    getRlTotalGoodsNum(row){
      return this.GoodsList.filter(goods => goods.toSuitListId === row.toSuitListId)
        .reduce((prev,cur)=>{
          return prev +cur.rlGoodsNum
        },0)
    },
  }
}
</script>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px;
  .header{
    //display: flex;
    //justify-content: space-between;
  }
  .content{
    padding: 20px 0 0;
  }
  .header-card{
    font-size: 14px;
    background-color: rgba(242, 242, 242, 1);
    p{
      margin: 10px 0;
      padding: 0;
    }
    .font-bold{
      font-weight: bold;
    }
    .true-number{
      color: #FF0000;
      font-weight: 600;
    }
  }
}
.goods-table{
  width: 1500px;
  .goods-title{
    font-size: 14px;
  }
  .goods-attr{
    font-size: 13px;
    color: #7F7F7F;
  }
}
.table-tips{

}

.header-card{
  position: relative;
  .button{
    position: absolute;
    display: flex;
    flex-direction: column;
    right: 20px;
    top: 30px;
  }
}
.box-content{
  font-size: 15px;
}
</style>
